package com.example.lib_core.util.presenter

import android.app.Activity
import android.graphics.Rect
import com.example.lib_core.task.SingleTask


/**
 * 用于监听布局变化的Task
 * 不使用#ViewTreeObserver.OnGlobalLayoutListener
 * 是防止onGlobalLayout回调时间过长（渣代码刷新过慢的时候）
 */
class GlobalLayoutListenerTask(private val activity: Activity) : SingleTask<Unit>(){

    private val iKeyBoardCallbackList = mutableListOf<IKeyBoardCallback>()
    private var status = NONE
    private val interval = 100L

    /** 全屏时的高度 */
    private var fullScreenHeight = -1
    /** 状态栏高度 */
    private var statusBarHeight = -1

    override fun onTaskRun() {
        while (isRunning){
            try {
                //获取可视范围
                val rect = Rect()
                activity.window.decorView.getWindowVisibleDisplayFrame(rect)
                //获取屏幕高度
                val screenHeight = getFullScreenHeight(activity)
                //获取状态栏高度
                val statueHeight = getStatueBarHeight(activity)
                //获取被遮挡高度（键盘高度）(屏幕高度-状态栏高度-可视范围)
                val keyBoardHeight: Int = screenHeight - statusBarHeight - rect.height()
                //显示或者隐藏
                val isKeyBoardShow = keyBoardHeight >= screenHeight / 3
                //当首次或者和之前的状态不一致的时候会回调，反之不回调(用于当状态变化后才回调，防止多次调用)
                if (status == NONE || (isKeyBoardShow && status == HIDDEN) || (!isKeyBoardShow && status == SHOW)) {
                    if (isKeyBoardShow) {
                        status = SHOW
                        dispatchKeyBoardShowEvent()
                    } else {
                        status = HIDDEN
                        dispatchKeyBoardHiddenEvent()
                    }
                }
                Thread.sleep(interval)
            } catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    /**
     * 用于获取全屏时的整体高度
     *
     * @return 屏幕高度
     */
    private fun getFullScreenHeight(activity: Activity): Int {
        if (fullScreenHeight == -1){
            val vm = activity.windowManager
            fullScreenHeight = vm.defaultDisplay.height
        }
        return fullScreenHeight
    }

    /**
     * 用于获取状态栏高度
     *
     * @return 状态栏高度
     */
    private fun getStatueBarHeight(activity: Activity): Int {
        if (statusBarHeight == -1){
            val res = activity.resources
            val resId = res.getIdentifier("status_bar_height", "dimen", "android")
            statusBarHeight =  res.getDimensionPixelSize(resId)
        }
        return statusBarHeight;
    }

    /**
     * 添加监听回调
     *
     * @param callback 监听的回调类
     */
    fun addCallBack(callback: Any?){
        if (callback is IKeyBoardCallback)  iKeyBoardCallbackList.add(callback)
    }

    /**
     * 移除监听回调
     *
     * @param callback 监听的回调类
     */
    fun removeCallback(callback: Any?){
        if (callback is IKeyBoardCallback)  iKeyBoardCallbackList.remove(callback)
    }

    /**
     * 分发隐藏事件
     */
    private fun dispatchKeyBoardHiddenEvent(){
        for (callback in iKeyBoardCallbackList){
            callback.onKeyBoardHidden()
        }
    }

    /**
     * 分发显示事件
     */
    private fun dispatchKeyBoardShowEvent(){
        for (callback in iKeyBoardCallbackList){
            callback.onKeyBoardShow()
        }
    }

    /**
     * 判断是不是没有监听回调
     *
     * @return true:空 false:不空
     */
    fun isEmpty(): Boolean = iKeyBoardCallbackList.isEmpty()

    companion object {
        private const val NONE = 0;
        private const val SHOW = 1;
        private const val HIDDEN = 2;
    }
}